#!/usr/bin/env bash

# =============================================================================
# 配置区域 - 用户可以修改这些变量
# =============================================================================
SCRIPT_NAME="财财itkali linux"
SCRIPT_VERSION="2.314"
AUTHOR="AI Assistant"
LOG_DIR="/data/data/com.termux/files/home/logs"
LOG_FILE="${LOG_DIR}/zero_fix.log"
BACKUP_DIR="/data/data/com.termux/files/home/backups"
MAX_RETRIES=3
RETRY_DELAY=2
DEBUG_MODE=false
# =============================================================================

# 颜色定义
readonly RED='\033[1;31m'
readonly GREEN='\033[1;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[1;34m'
readonly CYAN='\033[1;36m'
readonly PURPLE='\033[1;35m'
readonly WHITE='\033[1;37m'
readonly GRAY='\033[1;90m'
readonly NC='\033[0m' # 无颜色
# 全局变量
ANDROID_VERSION=""
CONNECT_ADDRESS=""
PAIRING_PORT=""
PAIRING_CODE=""
CONNECT_PORT=""
DEVICE_IP=""
AUTO_MODE=false
DEVICE_MODEL=""
DEVICE_SDK=""
CURRENT_TIMESTAMP=$(date +%s)
SESSION_ID=$(echo "${CURRENT_TIMESTAMP}_${RANDOM}" | md5sum | cut -c1-8 2>/dev/null || echo "${CURRENT_TIMESTAMP}_${RANDOM}")

# 表情符号
readonly E_OK="✅"
readonly E_ERROR="❌"
readonly E_WARN="⚠️"
readonly E_INFO="ℹ️"
readonly E_DEBUG="🐛"
readonly E_TIME="⏰"
readonly E_NETWORK="📡"
readonly E_DEVICE="📱"
readonly E_SETTINGS="⚙️"
readonly E_LOCK="🔒"
readonly E_KEY="🔑"
readonly E_LINK="🔗"
readonly E_SEARCH="🔍"
readonly E_DOWNLOAD="📥"
readonly E_UPLOAD="📤"
readonly E_SUCCESS="🎉"
readonly E_FAIL="💥"

# 进度动画函数
show_spinner() {
    local pid=$1
    local text="$2"
    local delay=0.1
    local frames=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
    local i=0
    
    while kill -0 "$pid" 2>/dev/null; do
        i=$(( (i+1) % 10 ))
        printf "\r%s %s" "${CYAN}${frames[i]}${NC}" "${text}"
        sleep "$delay"
    done
    printf "\r%s %s\n" "${GREEN}${E_OK}${NC}" "${text}"
}

# 日志记录函数
log_message() {
    local level="$1"
    local message="$2"
    local display="$3"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # 创建日志目录（如果不存在）
    mkdir -p "${LOG_DIR}"
    
    # 写入日志文件
    echo "[${timestamp}] [${SESSION_ID}] [${level}] ${message}" >> "${LOG_FILE}"
    
    # 显示消息（如果有）
    if [[ -n "${display}" ]]; then
        echo -e "${display}"
    fi
}

# 调试日志
debug_log() {
    if [[ "${DEBUG_MODE}" == true ]]; then
        log_message "DEBUG" "$1" "${GRAY}${E_DEBUG} $1${NC}"
    fi
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 检查网络连接
check_network() {
    log_message "INFO" "检查网络连接..." "${BLUE}${E_NETWORK} 检查网络连接...${NC}"
    
    if command_exists ping; then
        if ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1; then
            log_message "INFO" "网络连接正常" "${GREEN}${E_OK} 网络连接正常${NC}"
            return 0
        fi
    fi
    
    # 尝试使用curl检查网络
    if command_exists curl; then
        if curl -s --connect-timeout 5 http://www.baidu.com >/dev/null 2>&1; then
            log_message "INFO" "网络连接正常" "${GREEN}${E_OK} 网络连接正常${NC}"
            return 0
        fi
    fi
    
    log_message "WARN" "网络连接可能有问题" "${YELLOW}${E_WARN} 网络连接可能有问题${NC}"
    return 1
}

# 显示横幅
show_banner() {
    clear
    echo -e "${PURPLE}"
    echo "  ██████╗ █████╗ ██╗ ██████╗ █████╗ ██╗"
    echo " ██╔════╝██╔══██╗██║██╔════╝██╔══██╗██║"
    echo " ██║     ███████║██║██║     ███████║██║"
    echo " ██║     ██╔══██║██║██║     ██╔══██║██║"
    echo " ╚██████╗██║  ██║██║╚██████╗██║  ██║██║"
    echo "  ╚═════╝╚═╝  ╚═╝╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝"
    
    echo -e "${BLUE}"
    echo " ✦・・・・・✦・・・・・✦・・・・・✦・・・・・✦"
    
    echo -e "${CYAN}"
    echo " ██╗  ██╗ █████╗ ██╗     ██╗"
    echo " ██║ ██╔╝██╔══██╗██║     ██║"
    echo " █████╔╝ ███████║██║     ██║"
    echo " ██╔═██╗ ██╔══██║██║     ██║"
    echo " ██║  ██╗██║  ██║███████╗██║"
    echo " ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝"
    
    echo -e "${CYAN}╔════════════════════════════════════════╗"
    echo -e "║          ${WHITE}✦财财IT团队技术支持✦${CYAN}          ║"
    echo -e "║              ${WHITE}✦Version ${SCRIPT_VERSION}✦${CYAN}             ║"
    echo -e "╚════════════════════════════════════════╝${NC}"
    echo
}

# 显示系统信息
show_system_info() {
    log_message "INFO" "收集系统信息..." "${BLUE}${E_INFO} 收集系统信息...${NC}"
    
    # 获取设备信息
    if command_exists termux-info; then
        DEVICE_INFO=$(termux-info 2>/dev/null | head -10)
        log_message "DEBUG" "Termux信息: ${DEVICE_INFO}" ""
    fi
    
    # 获取Android SDK版本
    if command_exists getprop; then
        DEVICE_SDK=$(getprop ro.build.version.sdk 2>/dev/null)
        DEVICE_MODEL=$(getprop ro.product.model 2>/dev/null)
        ANDROID_RELEASE=$(getprop ro.build.version.release 2>/dev/null)
        
        log_message "INFO" "设备: ${DEVICE_MODEL}, Android: ${ANDROID_RELEASE} (SDK: ${DEVICE_SDK})" \
            "${CYAN}${E_DEVICE} 设备: ${DEVICE_MODEL}, Android: ${ANDROID_RELEASE} (SDK: ${DEVICE_SDK})${NC}"
    else
        log_message "WARN" "无法获取设备属性" "${YELLOW}${E_WARN} 无法获取设备属性${NC}"
    fi
    
    # 显示存储信息
    if command_exists df; then
        STORAGE_INFO=$(df -h /data 2>/dev/null | tail -1 || echo "无法获取存储信息")
        log_message "DEBUG" "存储信息: ${STORAGE_INFO}" ""
    fi
}

# 初始化脚本
init_script() {
    # 创建必要的目录
    mkdir -p "${LOG_DIR}" "${BACKUP_DIR}"
    
    # 记录脚本启动
    log_message "INFO" "脚本启动: ${SCRIPT_NAME} v${SCRIPT_VERSION}" ""
    log_message "INFO" "会话ID: ${SESSION_ID}" "${GRAY}会话ID: ${SESSION_ID}${NC}"
    
    # 显示系统信息
    show_system_info
    
    # 检查网络连接
    check_network
}

# 检查并安装必要工具
check_dependencies() {
    log_message "INFO" "检查系统依赖..." "${BLUE}${E_SEARCH} 检查系统依赖...${NC}"
    
    local missing_deps=()
    local packages=()
    
    # 检查 ADB
    if ! command_exists adb; then
        missing_deps+=("ADB")
        packages+=("android-tools")
    fi
    
    # 检查 curl
    if ! command_exists curl; then
        missing_deps+=("curl")
        packages+=("curl")
    fi
    
    # 检查其他有用工具
    if ! command_exists wget; then
        packages+=("wget")
    fi
    
    # 如果有缺失的依赖
    if [ ${#missing_deps[@]} -ne 0 ]; then
        log_message "WARN" "缺少依赖: ${missing_deps[*]}" "${YELLOW}${E_WARN} 缺少以下依赖: ${missing_deps[*]}${NC}"
        log_message "INFO" "正在安装缺失的依赖..." "${CYAN}${E_DOWNLOAD} 正在安装缺失的依赖...${NC}"
        
        if [ ${#packages[@]} -ne 0 ]; then
            (
                pkg update -y > /dev/null 2>&1
                for pkg_name in "${packages[@]}"; do
                    pkg install -y "$pkg_name" > /dev/null 2>&1
                done
            ) &
            local pid=$!
            show_spinner "$pid" "安装依赖包"
            wait "$pid"
            
            # 验证安装
            for dep in "${missing_deps[@]}"; do
                if [[ "$dep" == "ADB" ]] && ! command_exists adb; then
                    log_message "ERROR" "ADB 安装失败" "${RED}${E_ERROR} ADB 安装失败，请手动运行: pkg install android-tools${NC}"
                    return 1
                elif [[ "$dep" == "curl" ]] && ! command_exists curl; then
                    log_message "ERROR" "Curl 安装失败" "${RED}${E_ERROR} Curl 安装失败，请手动运行: pkg install curl${NC}"
                    return 1
                fi
            done
        fi
    fi
    
    log_message "INFO" "所有依赖已就绪" "${GREEN}${E_OK} 所有依赖已就绪${NC}"
    return 0
}

# 显示菜单
show_menu() {
    echo -e "${BLUE}📋 主菜单:${NC}"
    echo -e "  ${GREEN}1)${NC} 安装财财ITKali Linux脚本"
    echo -e "  ${GREEN}2)${NC} 自动修复 Signal 9 错误"
    echo -e "  ${GREEN}3)${NC} 手动选择 Android 版本修复"
    echo -e "  ${GREEN}4)${NC} 查看日志文件"
    echo -e "  ${GREEN}5)${NC} 重置 ADB 连接"
    echo -e "  ${GREEN}6)${NC} 检查系统状态"
    echo -e "  ${GREEN}7)${NC} 备份/恢复设置"
    echo -e "  ${GREEN}8)${NC} 高级选项"
    echo -e "  ${GREEN}9)${NC} 关于本工具"
    echo -e "  ${GREEN}10)${NC} 退出"
    echo
}

# 高级选项菜单
show_advanced_menu() {
    echo -e "${BLUE}🔧 高级选项:${NC}"
    echo -e "  ${GREEN}1)${NC} 启用调试模式"
    echo -e "  ${GREEN}2)${NC} 清除日志文件"
    echo -e "  ${GREEN}3)${NC} 测试 ADB 连接"
    echo -e "  ${GREEN}4)${NC} 检查更新"
    echo -e "  ${GREEN}5)${NC} 返回主菜单"
    echo
}

# 关于信息
show_about() {
    clear
    echo -e "${PURPLE}╔══════════════════════════════════════════════════════════╗${NC}"
    echo -e "${PURPLE}║${CYAN}                      关于                         ${PURPLE}║${NC}"
    echo -e "${PURPLE}║${WHITE}                 ${SCRIPT_NAME}                  ${PURPLE}║${NC}"
    echo -e "${PURPLE}║${YELLOW}                  版本 ${SCRIPT_VERSION}                        ${PURPLE}║${NC}"
    echo -e "${PURPLE}║${GRAY}            作者: ${AUTHOR}                ${PURPLE}║${NC}"
    echo -e "${PURPLE}╚══════════════════════════════════════════════════════════╝${NC}"
    
    echo -e "${PURPLE}"
    echo "  ██████╗ █████╗ ██╗ ██████╗ █████╗ ██╗"
    echo " ██╔════╝██╔══██╗██║██╔════╝██╔══██╗██║"
    echo " ██║     ███████║██║██║     ███████║██║"
    echo " ██║     ██╔══██║██║██║     ██╔══██║██║"
    echo " ╚██████╗██║  ██║██║╚██████╗██║  ██║██║"
    echo "  ╚═════╝╚═╝  ╚═╝╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝"
    
    echo -e "${BLUE}"
    echo " ✦・・・・・✦・・・・・✦・・・・・✦・・・・・✦"
    
    echo -e "${CYAN}"
    echo " ██╗  ██╗ █████╗ ██╗     ██╗"
    echo " ██║ ██╔╝██╔══██╗██║     ██║"
    echo " █████╔╝ ███████║██║     ██║"
    echo " ██╔═██╗ ██╔══██║██║     ██║"
    echo " ██║  ██╗██║  ██║███████╗██║"
    echo " ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝"
    echo -e "${NC}"
    
    echo
    echo -e "${CYAN}作者:${NC}"
    echo -e "  财财it制作"
    echo -e "  安装中间遇到任何问题直接问财财it客服"
    echo -e "  可以在财财it客服直接问"
    echo -e "  我看到我会第一时间回复您"
    echo -e "  我们主打卖的就是一个售后，一周之内有任何问题，随时来问我"
    echo
    echo -e "${CYAN}描述:${NC}"
    echo -e "  专为解决 kali linux Signal 9 错误而设计的强大工具。"
    echo
    echo -e "${CYAN}功能特点:${NC}"
    echo -e "  ${GREEN}✓${NC} 安装kali linux Android 版本"
    echo -e "  ${GREEN}✓${NC} 自动检测 Android 版本"
    echo -e "  ${GREEN}✓${NC} 智能修复流程"
    echo -e "  ${GREEN}✓${NC} 详细的日志记录"
    echo -e "  ${GREEN}✓${NC} 备份和恢复功能"
    echo -e "  ${GREEN}✓${NC} 用户友好的界面"
    echo
    echo -e "${CYAN}支持:${NC}"
    echo -e "  适用于 Android 12 及以上版本"
    echo -e "${CYAN}联系或反馈bug添加好友:${NC}"
    echo -e "${CYAN}v：it8888cai${NC}"
    echo
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo
}

# 检测Android版本
detect_android_version() {
    log_message "INFO" "检测Android版本..." "${BLUE}${E_DEVICE} 检测Android版本...${NC}"
    
    # 尝试通过ADB获取Android版本
    if command_exists adb && [[ -n "$CONNECT_ADDRESS" ]]; then
        local version
        version=$(adb shell getprop ro.build.version.release 2>/dev/null | tr -d '\r' || echo "")
        if [[ -n "$version" ]]; then
            log_message "INFO" "检测到Android版本: $version" "${GREEN}${E_OK} 检测到Android版本: ${version}${NC}"
            
            # 提取主版本号
            local major_version
            major_version=$(echo "$version" | cut -d. -f1)
            
            if [[ "$major_version" -ge 13 ]]; then
                ANDROID_VERSION=2
                log_message "INFO" "自动选择: Android 13+ 配置" "${CYAN}自动选择: Android 13+ 配置${NC}"
            elif [[ "$major_version" -eq 12 ]]; then
                # 检查是否是12L(12.1)或更高
                local minor_version
                minor_version=$(echo "$version" | cut -d. -f2)
                if [[ -n "$minor_version" ]] && [[ "$minor_version" -ge 1 ]]; then
                    ANDROID_VERSION=2
                    log_message "INFO" "自动选择: Android 12L+ 配置" "${CYAN}自动选择: Android 12L+ 配置${NC}"
                else
                    ANDROID_VERSION=1
                    log_message "INFO" "自动选择: Android 12 配置" "${CYAN}自动选择: Android 12 配置${NC}"
                fi
            else
                log_message "WARN" "检测到Android ${version}，但此修复主要针对Android 12+" "${YELLOW}${E_WARN} 检测到Android ${version}，但此修复主要针对Android 12+${NC}"
                manual_version_selection
            fi
            return
        fi
    fi
    
    # 如果ADB检测失败，尝试其他方法
    log_message "WARN" "无法通过ADB检测版本，尝试替代方法..." "${YELLOW}${E_WARN} 无法通过ADB检测版本，尝试替代方法...${NC}"
    
    # 尝试使用Termux内置工具检测
    if command_exists getprop; then
        local version
        version=$(getprop ro.build.version.release 2>/dev/null || echo "")
        if [[ -n "$version" ]]; then
            log_message "INFO" "检测到Android版本: $version" "${GREEN}${E_OK} 检测到Android版本: ${version}${NC}"
            
            # 提取主版本号
            local major_version
            major_version=$(echo "$version" | cut -d. -f1)
            
            if [[ "$major_version" -ge 13 ]]; then
                ANDROID_VERSION=2
                log_message "INFO" "自动选择: Android 13+ 配置" "${CYAN}自动选择: Android 13+ 配置${NC}"
            elif [[ "$major_version" -eq 12 ]]; then
                ANDROID_VERSION=1
                log_message "INFO" "自动选择: Android 12 配置" "${CYAN}自动选择: Android 12 配置${NC}"
            else
                log_message "WARN" "检测到Android ${version}，但此修复主要针对Android 12+" "${YELLOW}${E_WARN} 检测到Android ${version}，但此修复主要针对Android 12+${NC}"
                manual_version_selection
            fi
            return
        fi
    fi
    
    # 如果所有方法都失败，要求用户手动选择
    log_message "WARN" "无法自动检测Android版本" "${YELLOW}${E_WARN} 无法自动检测Android版本${NC}"
    manual_version_selection
}

# 手动版本选择
manual_version_selection() {
    echo -e "${YELLOW}请手动选择你的Android版本:${NC}"
    echo -e "  ${GREEN}1)${NC} Android 12"
    echo -e "  ${GREEN}2)${NC} Android 12L 或 13+"
    echo
    
    while true; do
        read -rp "请输入选项 (1 或 2): " user_choice
        case $user_choice in
            1)
                ANDROID_VERSION=1
                log_message "INFO" "用户选择: Android 12" "${CYAN}已选择: Android 12${NC}"
                break
                ;;
            2)
                ANDROID_VERSION=2
                log_message "INFO" "用户选择: Android 12L/13+" "${CYAN}已选择: Android 12L/13+${NC}"
                break
                ;;
            *)
                log_message "ERROR" "无效选项: $user_choice" "${RED}${E_ERROR} 无效选项，请重新选择!${NC}"
                ;;
        esac
    done
}

# 获取用户输入
get_user_input() {
    log_message "INFO" "获取用户输入..." "${BLUE}${E_LINK} 获取连接信息...${NC}"
    
    echo -e "${YELLOW}请在开发者选项的'无线调试'中查找以下信息:${NC}"
    echo
    
    # 获取IP和端口
    while true; do
        read -rp "请输入IP地址和端口 (例如: 192.168.1.2:8888): " PAIRING_PORT
        
        # 验证输入格式
        if [[ $PAIRING_PORT =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+$ ]]; then
            break
        else
            log_message "ERROR" "无效的IP:端口格式" "${RED}${E_ERROR} 格式错误! 请使用 IP:端口 格式${NC}"
        fi
    done
    
    # 获取配对码
    while true; do
        read -rp "请输入配对码 (6位数字): " PAIRING_CODE
        
        if [[ $PAIRING_CODE =~ ^[0-9]{6}$ ]]; then
            break
        else
            log_message "ERROR" "无效的配对码格式" "${RED}${E_ERROR} 配对码必须是6位数字!${NC}"
        fi
    done
    
    log_message "INFO" "用户输入: IP:端口=$PAIRING_PORT, 配对码=$PAIRING_CODE" "${GREEN}${E_OK} 输入信息已保存${NC}"
}

# 执行ADB配对
perform_pairing() {
    log_message "INFO" "开始设备配对..." "${BLUE}${E_KEY} 开始设备配对...${NC}"
    
    local retry_count=0
    local success=false
    
    while [[ $retry_count -lt $MAX_RETRIES && $success == false ]]; do
        retry_count=$((retry_count + 1))
        
        (adb pair "$PAIRING_PORT" "$PAIRING_CODE" > /dev/null 2>&1) &
        local pid=$!
        show_spinner "$pid" "尝试配对 (尝试 $retry_count/$MAX_RETRIES)"
        wait "$pid"
        local result=$?
        
        if [[ $result -eq 0 ]]; then
            success=true
        else
            log_message "WARN" "配对尝试 $retry_count 失败" "${YELLOW}${E_WARN} 配对尝试 $retry_count/$MAX_RETRIES 失败${NC}"
            if [[ $retry_count -lt $MAX_RETRIES ]]; then
                sleep "$RETRY_DELAY"
            fi
        fi
    done
    
    if [[ $success == false ]]; then
        log_message "ERROR" "配对失败" "${RED}${E_ERROR} 配对失败! 请检查:${NC}"
        echo -e "  - IP地址和端口是否正确"
        echo -e "  - 配对码是否正确"
        echo -e "  - 无线调试是否已开启"
        return 1
    fi
    
    log_message "INFO" "配对成功" "${GREEN}${E_OK} 配对成功!${NC}"
    return 0
}

# 执行ADB连接
perform_connection() {
    log_message "INFO" "开始ADB连接..." "${BLUE}${E_NETWORK} 开始ADB连接...${NC}"
    
    echo -e "${YELLOW}配对成功后，无线调试界面会显示一个新的连接端口${NC}"
    
    while true; do
        read -rp "请输入新的连接端口号: " CONNECT_PORT
        
        if [[ -n "$CONNECT_PORT" ]] && [[ "$CONNECT_PORT" =~ ^[0-9]+$ ]]; then
            break
        else
            log_message "ERROR" "端口号无效" "${RED}${E_ERROR} 端口号必须是数字!${NC}"
        fi
    done
    
    DEVICE_IP=$(echo "$PAIRING_PORT" | cut -d: -f1)
    CONNECT_ADDRESS="${DEVICE_IP}:${CONNECT_PORT}"
    
    local retry_count=0
    local success=false
    
    while [[ $retry_count -lt $MAX_RETRIES && $success == false ]]; do
        retry_count=$((retry_count + 1))
        
        (adb connect "$CONNECT_ADDRESS" > /dev/null 2>&1) &
        local pid=$!
        show_spinner "$pid" "尝试连接 (尝试 $retry_count/$MAX_RETRIES)"
        wait "$pid"
        local result=$?
        
        if [[ $result -eq 0 ]]; then
            success=true
        else
            log_message "WARN" "连接尝试 $retry_count 失败" "${YELLOW}${E_WARN} 连接尝试 $retry_count/$MAX_RETRIES 失败${NC}"
            if [[ $retry_count -lt $MAX_RETRIES ]]; then
                sleep "$RETRY_DELAY"
            fi
        fi
    done
    
    if [[ $success == false ]]; then
        log_message "ERROR" "连接失败" "${RED}${E_ERROR} 连接失败!${NC}"
        return 1
    fi
    
    log_message "INFO" "连接成功" "${GREEN}${E_OK} 连接成功!${NC}"
    return 0
}

# 修改系统设置
modify_system_settings() {
    log_message "INFO" "开始修改系统设置..." "${BLUE}${E_SETTINGS} 开始修改系统设置...${NC}"
    
    # 检测Android版本
    detect_android_version
    
    if [[ "$ANDROID_VERSION" = "1" ]]; then
        log_message "INFO" "应用Android 12修复方案" "${CYAN}应用Android 12修复方案...${NC}"
        (adb shell device_config set_sync_disabled_for_tests persistent && \
         adb shell device_config put activity_manager max_phantom_processes 2147483647) > /dev/null 2>&1 &
        local pid=$!
        show_spinner "$pid" "修改Android 12进程限制"
        wait "$pid"
    elif [[ "$ANDROID_VERSION" = "2" ]]; then
        log_message "INFO" "应用Android 12L/13+修复方案" "${CYAN}应用Android 12L/13+修复方案...${NC}"
        (adb shell settings put global settings_enable_monitor_phantom_procs false) > /dev/null 2>&1 &
        local pid=$!
        show_spinner "$pid" "禁用Android 12L/13+进程监控"
        wait "$pid"
    else
        log_message "ERROR" "无效的Android版本选择" "${RED}${E_ERROR} 无效的Android版本选择!${NC}"
        return 1
    fi
    
    log_message "INFO" "系统设置修改完成" "${GREEN}${E_OK} 系统设置修改完成!${NC}"
    return 0
}

# 验证修复结果
verify_fix() {
    log_message "INFO" "验证修复结果..." "${BLUE}${E_SEARCH} 验证修复结果...${NC}"
    
    # 检查Android 12设置
    if [[ "$ANDROID_VERSION" = "1" ]]; then
        local max_phantom
        max_phantom=$(adb shell device_config get activity_manager max_phantom_processes 2>/dev/null || echo "")
        if [[ "$max_phantom" = "2147483647" ]]; then
            log_message "INFO" "Android 12修复验证成功" "${GREEN}${E_OK} Android 12修复验证成功${NC}"
        else
            log_message "WARN" "Android 12修复可能未完全生效" "${YELLOW}${E_WARN} Android 12修复可能未完全生效${NC}"
        fi
    # 检查Android 12L/13+设置
    elif [[ "$ANDROID_VERSION" = "2" ]]; then
        local monitor_setting
        monitor_setting=$(adb shell settings get global settings_enable_monitor_phantom_procs 2>/dev/null || echo "")
        if [[ "$monitor_setting" = "0" ]] || [[ "$monitor_setting" = "false" ]]; then
            log_message "INFO" "Android 12L/13+修复验证成功" "${GREEN}${E_OK} Android 12L/13+修复验证成功${NC}"
        else
            log_message "WARN" "Android 12L/13+修复可能未完全生效" "${YELLOW}${E_WARN} Android 12L/13+修复可能未完全生效${NC}"
        fi
    fi
}

# 备份当前设置
backup_settings() {
    log_message "INFO" "备份当前设置..." "${BLUE}${E_UPLOAD} 备份当前设置...${NC}"
    
    local backup_file="${BACKUP_DIR}/settings_backup_${SESSION_ID}.txt"
    
    # 创建备份目录
    mkdir -p "${BACKUP_DIR}"
    
    # 获取当前设置
    {
        echo "# ${SCRIPT_NAME} 设置备份"
        echo "# 备份时间: $(date)"
        echo "# 会话ID: ${SESSION_ID}"
        echo ""
        echo "ANDROID_VERSION=${ANDROID_VERSION}"
        echo "DEVICE_MODEL=${DEVICE_MODEL}"
        echo "DEVICE_SDK=${DEVICE_SDK}"
        echo ""
        
        if [[ "$ANDROID_VERSION" = "1" ]]; then
            local max_phantom
            max_phantom=$(adb shell device_config get activity_manager max_phantom_processes 2>/dev/null || echo "unknown")
            echo "MAX_PHANTOM_PROCESSES=${max_phantom}"
        elif [[ "$ANDROID_VERSION" = "2" ]]; then
            local monitor_setting
            monitor_setting=$(adb shell settings get global settings_enable_monitor_phantom_procs 2>/dev/null || echo "unknown")
            echo "MONITOR_PHANTOM_PROCS=${monitor_setting}"
        fi
    } > "${backup_file}"
    
    if [[ $? -eq 0 ]]; then
        log_message "INFO" "设置已备份到: ${backup_file}" "${GREEN}${E_OK} 设置已备份${NC}"
    else
        log_message "ERROR" "备份失败" "${RED}${E_ERROR} 备份失败${NC}"
    fi
}

# 完成提示
show_completion() {
    log_message "INFO" "完成修复流程" "${BLUE}${E_SUCCESS} 完成修复流程${NC}"
    
    # 备份当前设置
    backup_settings
    
    (adb disconnect "$CONNECT_ADDRESS" 2>/dev/null)
    log_message "INFO" "已断开ADB连接" "${CYAN}已断开ADB连接${NC}"
    
    echo
    echo -e "${GREEN}${E_OK} 所有操作已完成!${NC}"
    echo
    echo -e "${YELLOW}${E_INFO} 重要提示:${NC}"
    echo -e "  - 请${RED}重启你的手机${NC}使设置生效"
    echo -e "  - 重启后，ZeroTermux应该不会再出现Signal 9错误"
    echo -e "  - 如果问题仍然存在，请考虑在电池优化设置中排除ZeroTermux"
    echo
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    echo -e "${CYAN}           感谢使用本修复工具 😊             ${NC}"
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    
    # 等待用户按键
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo
}

# 查看日志
view_log() {
    clear
    echo -e "${BLUE}${E_INFO} 日志文件内容:${NC}"
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    
    if [[ -f "$LOG_FILE" ]]; then
        if [[ -s "$LOG_FILE" ]]; then
            # 显示最后20行日志
            tail -20 "$LOG_FILE"
        else
            echo -e "${YELLOW}${E_WARN} 日志文件为空${NC}"
        fi
    else
        echo -e "${RED}${E_ERROR} 日志文件不存在${NC}"
    fi
    
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo
}

# 重置ADB连接
reset_adb() {
    log_message "INFO" "重置ADB连接..." "${BLUE}${E_NETWORK} 重置ADB连接...${NC}"
    
    (adb kill-server 2>/dev/null) &
    local pid=$!
    show_spinner "$pid" "停止ADB服务"
    wait "$pid"
    
    (adb start-server 2>/dev/null) &
    pid=$!
    show_spinner "$pid" "启动ADB服务"
    wait "$pid"
    
    log_message "INFO" "ADB连接已重置" "${GREEN}${E_OK} ADB连接已重置${NC}"
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo
}

# 检查系统状态
check_system_status() {
    clear
    echo -e "${BLUE}${E_INFO} 系统状态检查:${NC}"
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    
    # 检查ADB
    if command_exists adb; then
        echo -e "${GREEN}${E_OK} ADB 已安装${NC}"
        local adb_version=$(adb version 2>/dev/null | head -1 || echo "未知版本")
        echo -e "  版本: $adb_version"
    else
        echo -e "${RED}${E_ERROR} ADB 未安装${NC}"
    fi
    
    # 检查Android版本
    if command_exists getprop; then
        local version
        version=$(getprop ro.build.version.release 2>/dev/null || echo "未知")
        if [[ -n "$version" ]]; then
            echo -e "${GREEN}${E_OK} Android 版本: $version${NC}"
        else
            echo -e "${YELLOW}${E_WARN} 无法获取Android版本${NC}"
        fi
    fi
    
    # 检查存储空间
    if command_exists df; then
        echo -e "${CYAN}存储空间:${NC}"
        df -h /data 2>/dev/null | grep -v "tmpfs" | while read -r line; do
            echo -e "  $line"
        done || echo -e "  ${YELLOW}无法获取存储信息${NC}"
    fi
    
    # 检查日志文件
    if [[ -f "$LOG_FILE" ]]; then
        local log_size
        log_size=$(du -h "$LOG_FILE" 2>/dev/null | cut -f1 || echo "未知")
        echo -e "${GREEN}${E_OK} 日志文件: $LOG_FILE ($log_size)${NC}"
    else
        echo -e "${YELLOW}${E_WARN} 日志文件不存在${NC}"
    fi
    
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo
}

# 安装财财ITKali Linux脚本
install_cai1_script() {
    log_message "INFO" "开始安装财财ITKali Linux脚本" "${BLUE}${E_DOWNLOAD} 开始安装财财ITKali Linux脚本...${NC}"
    
    # 检查curl是否安装
    if ! command_exists curl; then
        log_message "WARN" "curl未安装，正在安装..." "${YELLOW}${E_WARN} curl未安装，正在安装...${NC}"
        (pkg install curl -y > /dev/null 2>&1) &
        local pid=$!
        show_spinner "$pid" "安装curl"
        wait "$pid"
        
        if ! command_exists curl; then
            log_message "ERROR" "curl安装失败" "${RED}${E_ERROR} curl安装失败${NC}"
            return 1
        fi
    fi
    
    # 下载并执行脚本
    (curl -L -o cai1.sh https://gitee.com/cai-cai-it/cai/raw/master/cai1.sh 2>/dev/null) &
    local pid=$!
    show_spinner "$pid" "下载脚本"
    wait "$pid"
    
    if [[ $? -eq 0 ]] && [[ -f "cai1.sh" ]]; then
        log_message "INFO" "脚本下载成功" "${GREEN}${E_OK} 脚本下载成功${NC}"
        
        # 添加执行权限
        (chmod +x cai1.sh) &
        pid=$!
        show_spinner "$pid" "添加执行权限"
        wait "$pid"
        
        log_message "INFO" "正在执行财财ITKali Linux脚本..." "${CYAN}正在执行财财ITKali Linux脚本...${NC}"
        ./cai1.sh
        
        log_message "INFO" "财财ITKali Linux脚本执行完成" "${GREEN}${E_OK} 财财ITKali Linux脚本执行完成${NC}"
    else
        log_message "ERROR" "脚本下载失败" "${RED}${E_ERROR} 脚本下载失败${NC}"
        return 1
    fi
    
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo
    return 0
}

# 自动修复流程
auto_fix() {
    AUTO_MODE=true
    show_banner
    if ! check_dependencies; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    get_user_input
    if ! perform_pairing; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    if ! perform_connection; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    if ! modify_system_settings; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    verify_fix
    show_completion
}

# 手动修复流程
manual_fix() {
    AUTO_MODE=false
    show_banner
    if ! check_dependencies; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    get_user_input
    if ! perform_pairing; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    if ! perform_connection; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    
    # 手动选择版本
    manual_version_selection
    
    if ! modify_system_settings; then
        read -n 1 -s -r -p "按任意键返回主菜单..."
        return
    fi
    verify_fix
    show_completion
}

# 备份/恢复菜单
backup_restore_menu() {
    clear
    echo -e "${BLUE}${E_UPLOAD} 备份/恢复菜单:${NC}"
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    echo -e "  ${GREEN}1)${NC} 备份当前设置"
    echo -e "  ${GREEN}2)${NC} 查看备份列表"
    echo -e "  ${GREEN}3)${NC} 恢复设置"
    echo -e "  ${GREEN}4)${NC} 返回主菜单"
    echo -e "${PURPLE}══════════════════════════════════════════════════════════${NC}"
    
    local choice
    read -rp "请选择操作 [1-4]: " choice
    
    case $choice in
        1)
            backup_settings
            ;;
        2)
            echo -e "${CYAN}备份列表:${NC}"
            ls -la "${BACKUP_DIR}"/*.txt 2>/dev/null || echo -e "${YELLOW}没有找到备份文件${NC}"
            ;;
        3)
            echo -e "${YELLOW}恢复功能尚未实现${NC}"
            ;;
        4)
            return
            ;;
        *)
            echo -e "${RED}无效选择${NC}"
            ;;
    esac
    
    read -n 1 -s -r -p "按任意键继续..."
    echo
    backup_restore_menu
}

# 高级选项
advanced_options() {
    while true; do
        clear
        show_banner
        show_advanced_menu
        
        local choice
        read -rp "请选择操作 [1-5]: " choice
        
        case $choice in
            1)
                DEBUG_MODE=true
                echo -e "${GREEN}调试模式已启用${NC}"
                sleep 1
                ;;
            2)
                if [[ -f "$LOG_FILE" ]]; then
                    rm "$LOG_FILE"
                    echo -e "${GREEN}日志文件已清除${NC}"
                else
                    echo -e "${YELLOW}日志文件不存在${NC}"
                fi
                sleep 1
                ;;
            3)
                echo -e "${CYAN}测试ADB连接...${NC}"
                if command_exists adb; then
                    adb devices
                else
                    echo -e "${RED}ADB未安装${NC}"
                fi
                read -n 1 -s -r -p "按任意键继续..."
                ;;
            4)
                echo -e "${YELLOW}检查更新功能尚未实现${NC}"
                sleep 1
                ;;
            5)
                return
                ;;
            *)
                echo -e "${RED}无效选择${NC}"
                sleep 1
                ;;
        esac
    done
}

# 主菜单循环
main_menu() {
    while true; do
        show_banner
        show_menu
        
        local choice
        read -rp "请选择操作 [1-10]: " choice
        
        case $choice in
            1)
                install_cai1_script
                ;;
            2)
                auto_fix
                ;;
            3)
                manual_fix
                ;;
            4)
                view_log
                ;;
            5)
                reset_adb
                ;;
            6)
                check_system_status
                ;;
            7)
                backup_restore_menu
                ;;
            8)
                advanced_options
                ;;
            9)
                show_about
                ;;
            10)
                echo -e "${GREEN}👋 感谢使用，再见！${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}❌ 无效选择，请重新输入!${NC}"
                sleep 1
                ;;
        esac
    done
}

# 异常处理
trap 'echo -e "\n${RED}${E_ERROR} 用户中断操作${NC}"; log_message "ERROR" "用户中断操作"; exit 1' INT
trap 'log_message "INFO" "脚本正常退出" ""' EXIT

# 脚本入口
init_script
main_menu